import React  from 'react';
import PropTypes from 'proptypes';
const STYLE = {
  header: { fontSize: '0.85em', color: '#636363' },
  menu: { marginLeft: '5px' },
  item: { wordBreak: 'break-all', cursor: 'default' },
};

export default function TableSubmenu(props){
  const [state,setState]=React.useState({
  });
  React.useEffect(()=>{
    if (state.collapsed === undefined) {
      setState((state)=>({...state,collapsed: !!props.collapsed }));
    }
  },[props.collapsed]);
  const toggleCollapse=()=> {
    setState({ collapsed: !state.collapsed });
  }

  const renderSubMenuHeader=()=> {
    const { itemsByTable, table } = props;

    const title = state.collapsed ? 'Expand' : 'Collapse';
    const cssClass = state.collapsed ? 'right' : 'down';
    const cssStyle = { ...STYLE.header };
    if (!itemsByTable || !itemsByTable[table] || itemsByTable[table].length) {
      cssStyle.color = 'lightgray';
    }
    return (
      <span
        title={title}
        className="header clickable"
        onClick={toggleCollapse}
        style={cssStyle}
      >
        <i className={`${cssClass} triangle icon`} />
        {props.title}
      </span>
    );
  }

  const renderSubMenuItems=(table)=> {
    const { itemsByTable } = props;

    if (!itemsByTable || !itemsByTable[table] || state.collapsed) {
      return null;
    }

    if (!itemsByTable[table].length) {
      return (
        <span className="ui grey item">
          <i> No results found</i>
        </span>
      );
    }

    const cssStyle = { ...STYLE.item };
    if (state.collapsed) {
      cssStyle.display = 'none';
    } else {
      cssStyle.display = 'flex';
      cssStyle.justifyContent = 'space-between';
    }
    const columnsIcon = (
      <i
        className="columns icon"
        style={{ float: 'left', margin: '0 0.3em 0 0' }}
      />
    );
    const styleColumnType = {
      float: 'right',
      padding: '0 0.5em 0 0.5em',
      textTransform: 'uppercase',
    };

    return itemsByTable[table].map(item => (
      <span key={item.name} title={item.name} style={cssStyle} className="item">
        <span style={{ display: 'flex' }}>
          {props.title === 'Columns' ? columnsIcon : null}
          {item.name}
        </span>
        {props.title === 'Columns' ? (
          <span style={styleColumnType}>{item.dataType}</span>
        ) : null}
      </span>
    ));
  }

    const { table } = props;
    return (
      <div className="item">
        {renderSubMenuHeader()}
        <div className="menu" style={STYLE.menu}>
          {renderSubMenuItems(table)}
        </div>
      </div>
    );
}
